﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Bussiness.Entity;
using Bussiness.Manager;
using AF_ORM.CORE;
using MP.Core.Library;
using ComExcel = Microsoft.Office.Interop.Excel;
using System.Threading;
using DSC.uc;
namespace DSC
{
    public partial class ucMenu : AfUserControl
    {
        public DataTable dtHangMuc { set; get; }
        public ucMenu()
        {
            InitializeComponent();
            LoadUserSystem();
        }
        #region General Functions
        private void kryptonTabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (tabRole.SelectedTab.Name)
            {
                case "tabUserSystem":
                    LoadUserSystem();
                    break;
                case "tabAgent":
                    LoadAgent();
                    break;
                case "tabMotorGroup":
                    LoadMotorGroup();
                    break;
                case "tabMotorType":
                    LoadMotorType();
                    break;
                case "tabRootServices":
                    LoadHangMuc();
                    LoadDefault();
                    break;
                case "tabPTKMGT":
                    LoadPTGTKM();
                    break;
                case "tabPKTT":
                    LoadPTPKTT();
                    break;
                case "tabRoleFunction":
                    if (tabRoleFunction.Controls.Count == 0)
                    {
                        tabRoleFunction.Controls.Add(new ucRoleFunction());
                    }
                    break;
            }
        }
        public override void Search()
        {
            switch (tabRole.SelectedTab.Name)
            {
                case "tabUserSystem":
                    LoadUserSystem();
                    break;
                case "tabAgent":
                    LoadAgent();
                    break;
                case "tabMotorGroup":
                    LoadMotorGroup();
                    break;
                case "tabMotorType":
                    LoadMotorType();
                    break;
                case "tabRootServices":
                    LoadHangMuc();
                    break;
                case "tabPTKMGT":
                    LoadPTGTKM();
                    break;
                case "tabPKTT":
                    LoadPTPKTT();
                    break;
            }
        }
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.F3) // hien thi form them
            {
                switch (tabRole.SelectedTab.Name)
                {
                    case "tabUserSystem":
                        frmAgentDetail frm = new frmAgentDetail();
                        this.ShowChildForm(frm);
                        break;
                    case "tabAgent":
                        frmAgentDetail2 frm2 = new frmAgentDetail2();
                        this.ShowChildForm(frm2);
                        break;
                    case "tabMotorGroup":
                        frmMotorGroup frm1 = new frmMotorGroup();
                        this.ShowChildForm(frm1);
                        break;
                    case "tabMotorType":
                        frmMotorType frmmtType = new frmMotorType();
                        this.ShowChildForm(frmmtType);
                        break;
                    case "tabRootServices":
                        frmServiceDetail frmHM = new frmServiceDetail();
                        ShowChildForm(frmHM);
                        break;
                    case "tabPTKMGT":
                        frmToolGTKM frmTool = new frmToolGTKM();
                        this.ShowChildForm(frmTool);
                        break;
                    case "tabPKTT":
                        frmToolPKTT frmPKTT = new frmToolPKTT();
                        this.ShowChildForm(frmPKTT);
                        break;
                }
                return true;
            }
            if (keyData == Keys.F2) // hien thi form sua
            {
                switch (tabRole.SelectedTab.Name)
                {
                    case "tabUserSystem":
                        int ID = !string.IsNullOrEmpty(gridAgent["UserId", gridAgent.SelectedRows[0].Index].Value.ToString()) ? (int)gridAgent["UserId", gridAgent.SelectedRows[0].Index].Value : -1;
                        frmAgentDetail frm = new frmAgentDetail(ID);
                        this.ShowChildForm(frm);
                        break;
                    case "tabAgent":
                        int ID2 = !string.IsNullOrEmpty(gridAgent2["UserId2", gridAgent2.SelectedRows[0].Index].Value.ToString()) ? (int)gridAgent2["UserId2", gridAgent2.SelectedRows[0].Index].Value : -1;
                        frmAgentDetail2 frm2 = new frmAgentDetail2(ID2);
                        this.ShowChildForm(frm2);
                        break;
                    case "tabMotorGroup":
                        int GroupCode = !string.IsNullOrEmpty(gridGroup["ModelCodeG", gridGroup.SelectedRows[0].Index].Value.ToString()) ? int.Parse(gridGroup["ModelCodeG", gridGroup.SelectedRows[0].Index].Value.ToString()) : 0;
                        frmMotorGroup frm1 = new frmMotorGroup(GroupCode, true);
                        this.ShowChildForm(frm1);
                        break;
                    case "tabMotorType":
                        string ModelCode = !string.IsNullOrEmpty(gridMotorType["ModelCode", gridMotorType.SelectedRows[0].Index].Value.ToString()) ? (string)gridMotorType["ModelCode", gridMotorType.SelectedRows[0].Index].Value : "";
                        frmMotorType frmmtType = new frmMotorType(ModelCode, true);
                        this.ShowChildForm(frmmtType);
                        break;
                    case "tabRootServices":
                        int IDHM = !string.IsNullOrEmpty((string)gridHangMuc["Id", gridHangMuc.SelectedRows[0].Index].Value) ? int.Parse((string)gridHangMuc["Id", gridHangMuc.SelectedRows[0].Index].Value) : -1;
                        string ServiceCode = !string.IsNullOrEmpty((string)gridHangMuc["ServiceCode", gridHangMuc.SelectedRows[0].Index].Value) ? gridHangMuc["Id", gridHangMuc.SelectedRows[0].Index].Value.ToString() : "";
                        string Model = !string.IsNullOrEmpty((string)gridHangMuc["MotorType", gridHangMuc.SelectedRows[0].Index].Value) ? gridHangMuc["MotorType", gridHangMuc.SelectedRows[0].Index].Value.ToString() : "";
                        frmServiceDetail frmHM = new frmServiceDetail(IDHM,ServiceCode, Model, true);
                        ShowChildForm(frmHM);
                        break;
                    case "tabPTKMGT":
                        string Code = !string.IsNullOrEmpty(dtPTKMGT["CodePTKMGT", dtPTKMGT.SelectedRows[0].Index].Value.ToString()) ? (string)dtPTKMGT["CodePTKMGT", dtPTKMGT.SelectedRows[0].Index].Value : "";
                        frmToolGTKM frmTool = new frmToolGTKM(Code, true);
                        this.ShowChildForm(frmTool);
                        break;
                    case "tabPKTT":
                        string CodePKTT = !string.IsNullOrEmpty(gridPKTT["CodePKTT", gridPKTT.SelectedRows[0].Index].Value.ToString()) ? (string)gridPKTT["CodePKTT", gridPKTT.SelectedRows[0].Index].Value : "";
                        frmToolPKTT frmToolPKTT = new frmToolPKTT(CodePKTT, true);
                        this.ShowChildForm(frmToolPKTT);
                        break;
                }

                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }
        #endregion

        #region User System
        private void LoadUserSystem()
        {
            DataTable dt = PT_AccountManager.CreateInstant().GetAll(1);
            gridAgent.DataSource = dt;
        }
        private void btnAdd_Click(object sender, EventArgs e)
        {
            frmAgentDetail frm = new frmAgentDetail();
            this.ShowChildForm(frm);
        }
        private void btDelete_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Bạn có chắc là muốn xóa không?", "Thông Báo", MessageBoxButtons.YesNo);
            if (dlg == DialogResult.Yes)
            {
                string users = "";
                for (int i = 0; i < gridAgent.RowCount; i++)
                {
                    DataGridViewCheckBoxCell checkSelect = gridAgent.Rows[i].Cells[0] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value != null && (bool)checkSelect.Value == true)
                    {
                        int ID = !string.IsNullOrEmpty(gridAgent["UserId", i].Value.ToString()) ? (int)gridAgent["UserId", i].Value : -1;
                        if (ID != -1)
                        {
                            PT_AccountEntity obj = PT_AccountManager.CreateInstant().GetByID(ID);
                            if (obj != null)
                            {
                                obj.IsDeleted = true;
                                obj.UpdatedBy = SessionLogin.UserCode;
                                obj.UpdatedDate = DateTime.Now;
                                PT_AccountManager.CreateInstant().Update(obj);
                                if (!string.IsNullOrEmpty(users))
                                    users += ", ";
                                users += obj.UserCode;
                            }
                        }
                    }
                }
                if(!string.IsNullOrEmpty(users))
                    PT_ActionHistoryManager.CreateInstant().SaveHistory(SessionLogin.UserId, "Xóa user hệ thống", "Xóa các user hệ thống sau: " + users);
                LoadUserSystem();
            }
        }

        private void gridAgent_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1 && e.ColumnIndex == 0)
            {
                for (int i = 0; i < gridAgent.RowCount; i++)
                {
                    DataGridViewCheckBoxCell checkSelect = gridAgent.Rows[i].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value == null || (checkSelect.Value != null && (bool)checkSelect.Value == false))
                        checkSelect.Value = true;
                    else
                        checkSelect.Value = false;
                }
            }
        }

        private void gridAgent_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex > 0 && e.RowIndex > -1)
            {
                int ID = !string.IsNullOrEmpty(gridAgent["UserId", e.RowIndex].Value.ToString()) ? (int)gridAgent["UserId", e.RowIndex].Value : -1;
                frmAgentDetail frm = new frmAgentDetail(ID);
                this.ShowChildForm(frm);
            }
        }

        #endregion

        #region Agent
        private void LoadAgent()
        {
            DataTable dt = PT_AccountManager.CreateInstant().GetAll(0);
            gridAgent2.DataSource = dt;
        }
        private void btAddAgent_Click(object sender, EventArgs e)
        {
            frmAgentDetail2 frm = new frmAgentDetail2();
            this.ShowChildForm(frm);
        }

        private void btDeleteAgent_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Bạn có chắc là muốn xóa không?", "Thông Báo", MessageBoxButtons.YesNo);
            if (dlg == DialogResult.Yes)
            {
                string agents = "";
                for (int i = 0; i < gridAgent2.RowCount; i++)
                {
                    DataGridViewCheckBoxCell checkSelect = gridAgent2.Rows[i].Cells[0] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value != null && (bool)checkSelect.Value == true)
                    {
                        int ID = !string.IsNullOrEmpty(gridAgent2["UserId2", i].Value.ToString()) ? (int)gridAgent2["UserId2", i].Value : -1;
                        if (ID != -1)
                        {
                            PT_AccountEntity obj = PT_AccountManager.CreateInstant().GetByID(ID);
                            if (obj != null)
                            {
                                obj.IsDeleted = true;
                                obj.UpdatedBy = SessionLogin.UserCode;
                                obj.UpdatedDate = DateTime.Now;
                                PT_AccountManager.CreateInstant().Update(obj);
                                if (!string.IsNullOrEmpty(agents))
                                    agents += ", ";
                                agents += obj.UserName;
                            }
                        }
                    }
                }
                if(!string.IsNullOrEmpty(agents))
                    PT_ActionHistoryManager.CreateInstant().SaveHistory(SessionLogin.UserId, "Xóa nhân viên", "Xóa các nhân viên sau:" + agents);
                LoadAgent();
            }
        }

        private void gridAgent2_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1 && e.ColumnIndex == 0)
            {
                for (int i = 0; i < gridAgent2.RowCount; i++)
                {
                    DataGridViewCheckBoxCell checkSelect = gridAgent2.Rows[i].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value == null || (checkSelect.Value != null && (bool)checkSelect.Value == false))
                        checkSelect.Value = true;
                    else
                        checkSelect.Value = false;
                }
            }
        }
        private void gridAgent2_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex > 0 && e.RowIndex > -1)
            {
                int ID = !string.IsNullOrEmpty(gridAgent2["UserId2", e.RowIndex].Value.ToString()) ? (int)gridAgent2["UserId2", e.RowIndex].Value : -1;
                frmAgentDetail2 frm = new frmAgentDetail2(ID);
                this.ShowChildForm(frm);
            }
        }
        #endregion

        #region Motor Groups
        // Motor Group
        public void LoadMotorGroup()
        {
            PT_HondaModelGroupEntity optionObj = new PT_HondaModelGroupEntity();
            optionObj.IsDeleted = false;
            SelectOptions option = new SelectOptions();
            option.AddSortField("OrderIndex", true);
            DataTable lst = PT_HondaModelGroupManager.CreateInstant().SelectWithCondition(optionObj, option);
            DataTable dt = new DataTable();
            dt.Columns.Add("ModelCode");
            dt.Columns.Add("STT");
            dt.Columns.Add("LoaiXe");
            dt.Columns.Add("ThuTu");
            dt.Columns.Add("Status");
            dt.Columns.Add("CreatedDate");
            for (int i = 0; i < lst.Rows.Count; i++)
            {
                DataRow dr = dt.NewRow();
                dr["ModelCode"] = lst.Rows[i]["GroupCode"].ToString();
                dr["STT"] = (i + 1).ToString();
                dr["LoaiXe"] = lst.Rows[i]["GroupName"].ToString();
                dr["ThuTu"] = lst.Rows[i]["OrderIndex"].ToString();
                dr["Status"] = (bool)lst.Rows[i]["IsActive"] == true ? "Đang hoạt động" : "Không hoạt động";
                dr["CreatedDate"] = ((DateTime)lst.Rows[i]["CreatedDate"]).ToString("dd/MM/yyyy");
                dt.Rows.Add(dr);
            }
            gridGroup.DataSource = dt;
        }
        private void gridGroup_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1 && gridGroup.Columns[e.ColumnIndex].Name == "checkSelectG")
            {
                for (int i = 0; i < gridGroup.RowCount; i++)
                {
                    DataGridViewCheckBoxCell checkSelect = gridGroup.Rows[i].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value == null || (checkSelect.Value != null && (bool)checkSelect.Value == false))
                        checkSelect.Value = true;
                    else
                        checkSelect.Value = false;
                }
            }
        }

        private void gridGroup_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex > 0 && e.RowIndex > -1)
            {
                int ModelCode = !string.IsNullOrEmpty(gridGroup["ModelCodeG", e.RowIndex].Value.ToString()) ? int.Parse(gridGroup["ModelCodeG", e.RowIndex].Value.ToString()) : 0;
                frmMotorGroup frm = new frmMotorGroup(ModelCode, true);
                this.ShowChildForm(frm);
            }
        }

        private void btaddGroup_Click(object sender, EventArgs e)
        {
            frmMotorGroup frm = new frmMotorGroup();
            this.ShowChildForm(frm);
        }

        private void btDeleteGroup_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Bạn có chắc là muốn xóa không?", "Thông Báo", MessageBoxButtons.YesNo);
            if (dlg == DialogResult.Yes)
            {
                string motorGroup = "";
                string lstKhongTheXoa = "";
                for (int i = 0; i < gridGroup.RowCount; i++)
                {
                    DataGridViewCheckBoxCell checkSelect = gridGroup.Rows[i].Cells[0] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value != null && (bool)checkSelect.Value == true)
                    {
                        int ModelCode = !string.IsNullOrEmpty(gridGroup["ModelCodeG", i].Value.ToString()) ? int.Parse(gridGroup["ModelCodeG", i].Value.ToString()) : 0;
                        if (ModelCode != 0)
                        {
                            // kiem tra nhom xe nay co chua loai xe nao khong, neu co thi khong cho phep xoa
                            PT_HondaModelEntity option = new PT_HondaModelEntity();
                            option.GroupCode = ModelCode;
                            option.IsDeleted = false;
                            option.IsActive = true;
                            DataTable dt = PT_HondaModelManager.CreateInstant().SelectWithCondition(option);
                            if (dt.Rows.Count > 0)
                            {
                                if (!string.IsNullOrEmpty(lstKhongTheXoa))
                                    lstKhongTheXoa += ", ";
                                string GroupName = !string.IsNullOrEmpty(gridGroup["LoaiXeG", i].Value.ToString()) ? gridGroup["LoaiXeG", i].Value.ToString() : "";
                                lstKhongTheXoa += GroupName;
                            }
                            else
                            {
                                PT_HondaModelGroupEntity obj = PT_HondaModelGroupManager.CreateInstant().GetByGroupCode(ModelCode);
                                if (obj != null)
                                {
                                    obj.IsDeleted = true;
                                    obj.UpdatedBy = SessionLogin.UserCode;
                                    obj.UpdatedDate = DateTime.Now;
                                    PT_HondaModelGroupManager.CreateInstant().Update(obj);
                                    if (!string.IsNullOrEmpty(motorGroup))
                                        motorGroup += ", ";
                                    motorGroup += obj.GroupName;
                                }
                            }
                        }
                    }
                }
                LoadMotorGroup();
                if (!string.IsNullOrEmpty(motorGroup))
                {
                    PT_ActionHistoryManager.CreateInstant().SaveHistory(SessionLogin.UserId, "Xóa nhóm xe", "Xóa các nhóm xe sau: " + motorGroup + "\rCác nhớm xe sau không thể xóa vì cơ sở dữ liệu có chứa loại xe thuộc nhóm này: " + lstKhongTheXoa);
                }
            }
        }
        #endregion

        #region Motor Types
        private void LoadMotorType()
        {
            DataTable lst = PT_HondaModelManager.CreateInstant().GetAll();
            DataTable dt = new DataTable();
            dt.Columns.Add("STT");
            dt.Columns.Add("ModelCode");
            dt.Columns.Add("LoaiXe");
            dt.Columns.Add("NhomXe");
            dt.Columns.Add("Status");
            dt.Columns.Add("CreatedDate");
            for (int i = 0; i < lst.Rows.Count; i++)
            {
                DataRow dr = dt.NewRow();
                dr["STT"] = (i + 1).ToString();
                dr["ModelCode"] = lst.Rows[i]["ModelCode"].ToString();
                dr["LoaiXe"] = lst.Rows[i]["ModelName"].ToString();
                dr["NhomXe"] = lst.Rows[i]["GroupName"].ToString();
                dr["Status"] = (bool)lst.Rows[i]["IsActive"] == true ? "Đang hoạt động" : "Không hoạt động";
                dr["CreatedDate"] = ((DateTime)lst.Rows[i]["CreatedDate"]).ToString("dd/MM/yyyy");
                dt.Rows.Add(dr);
            }
            gridMotorType.DataSource = dt;
        }
        private void btAdd_Click(object sender, EventArgs e)
        {
            frmMotorType frm = new frmMotorType();
            this.ShowChildForm(frm);
        }

        private void kryptonButton1_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Bạn có chắc là muốn xóa không?", "Thông Báo", MessageBoxButtons.YesNo);
            if (dlg == DialogResult.Yes)
            {
                string motorTypes = "";
                for (int i = 0; i < gridMotorType.RowCount; i++)
                {
                    DataGridViewCheckBoxCell checkSelect = gridMotorType.Rows[i].Cells[0] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value != null && (bool)checkSelect.Value == true)
                    {
                        string ModelCode = !string.IsNullOrEmpty(gridMotorType["ModelCode", i].Value.ToString()) ? (string)gridMotorType["ModelCode", i].Value : "";
                        if (!string.IsNullOrEmpty(ModelCode))
                        {
                            PT_HondaModelEntity obj = PT_HondaModelManager.CreateInstant().GetByModelCode(ModelCode);
                            if (obj != null)
                            {
                                obj.IsDeleted = true;
                                obj.UpdatedBy = SessionLogin.UserCode;
                                obj.UpdatedDate = DateTime.Now;
                                PT_HondaModelManager.CreateInstant().Update(obj);
                                if (!string.IsNullOrEmpty(motorTypes))
                                    motorTypes += ", ";
                                motorTypes += obj.ModelName;
                            }
                        }
                    }
                }
                LoadMotorType();
                // history
                if (!string.IsNullOrEmpty(motorTypes))
                {
                    PT_ActionHistoryManager.CreateInstant().SaveHistory(SessionLogin.UserId, "Xóa loại xe", "Xóa các loại xe sau: " + motorTypes);
                }
            }
        }

        private void gridMotorType_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1 && e.ColumnIndex == 0)
            {
                for (int i = 0; i < gridMotorType.RowCount; i++)
                {
                    DataGridViewCheckBoxCell checkSelect = gridMotorType.Rows[i].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value == null || (checkSelect.Value != null && (bool)checkSelect.Value == false))
                        checkSelect.Value = true;
                    else
                        checkSelect.Value = false;
                }
            }
        }

        private void gridMotorType_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex > 0 && e.RowIndex > -1)
            {
                string ModelCode = !string.IsNullOrEmpty(gridMotorType["ModelCode", e.RowIndex].Value.ToString()) ? (string)gridMotorType["ModelCode", e.RowIndex].Value : "";
                frmMotorType frm = new frmMotorType(ModelCode, true);
                this.ShowChildForm(frm);
            }
        }
        #endregion 

        #region Hang muc sua chua
        private void LoadHangMuc()
        {
            DataTable lst = PT_ServiceListManager.CreateInstant().GetAll();
            DataTable dt = new DataTable();
            dt.Columns.Add("Id");
            dt.Columns.Add("STT");
            dt.Columns.Add("ServiceCode");
            dt.Columns.Add("MotorType");
            dt.Columns.Add("ServiceName");
            dt.Columns.Add("AgentPrice");
            dt.Columns.Add("Price");
            dt.Columns.Add("ServiceType");
            dt.Columns.Add("CanEditNoiDung");
            dt.Columns.Add("CanEditGiaBan");
            dt.Columns.Add("CanEditGiamGia");
            dt.Columns.Add("CanEditGCN");
            for (int i = 0; i < lst.Rows.Count; i++)
            {
                DataRow dr = dt.NewRow();
                dr["Id"] = lst.Rows[i]["Id"].ToString();
                dr["STT"] = (i + 1).ToString();
                dr["ServiceCode"] = lst.Rows[i]["ServiceCode"].ToString();
                if (lst.Rows[i]["ModelCode"].ToString().CompareTo("ALL") == 0)
                    dr["MotorType"] = "Tất cả";
                else
                    dr["MotorType"] = lst.Rows[i]["ModelCode"].ToString();
                dr["ServiceName"] = lst.Rows[i]["ServiceName"];
                dr["AgentPrice"] = String.Format("{0:0,0.###}", double.Parse(lst.Rows[i]["AgentPrice"].ToString()));
                dr["Price"] = String.Format("{0:0,0.###}", double.Parse(lst.Rows[i]["Price"].ToString()));
                string type = "";
                switch (lst.Rows[i]["ServiceType"].ToString())
                {
                    case "SC":
                        type = "Sửa chữa";
                        break;
                    case "RB":
                        type = "Ráp bán";
                        break;
                    case "KTDK":
                        type = "Kiểm tra định kỳ";
                        break;
                    case "GCN":
                        type = "Gia công ngoài";
                        break;
                }
                dr["ServiceType"] = type;
               
                string CanEditNoiDung = "";
                switch (bool.Parse(lst.Rows[i]["CanEditNoiDung"].ToString()))
                {
                    case true:
                        CanEditNoiDung = "Có";
                        break;
                    case false:
                        CanEditNoiDung = "Không";
                        break;
                }
                dr["CanEditNoiDung"] = CanEditNoiDung;

                string CanEditGiaBan = "";
                switch (bool.Parse(lst.Rows[i]["CanEditGiaBan"].ToString()))
                {
                    case true:
                        CanEditGiaBan = "Có";
                        break;
                    case false:
                        CanEditGiaBan = "Không";
                        break;
                }
                dr["CanEditGiaBan"] = CanEditGiaBan;

                string CanEditGiamGia = "";
                switch (bool.Parse(lst.Rows[i]["CanEditGiamGia"].ToString()))
                {
                    case true:
                        CanEditGiamGia = "Có";
                        break;
                    case false:
                        CanEditGiamGia = "Không";
                        break;
                }
                dr["CanEditGiamGia"] = CanEditGiamGia;

                string CanEditGCN = "";
                switch (bool.Parse(lst.Rows[i]["CanEditGCN"].ToString()))
                {
                    case true:
                        CanEditGCN = "Có";
                        break;
                    case false:
                        CanEditGCN = "Không";
                        break;
                }
                dr["CanEditGCN"] = CanEditGCN;
                dt.Rows.Add(dr);
            }
            gridHangMuc.DataSource = dt;
            if(lst.Rows.Count>0)
                lbNgayKhoiTao.Text = lst.Rows[0]["CreatedDate"] != null && !string.IsNullOrEmpty(lst.Rows[0]["CreatedDate"].ToString()) ? "Ngày khởi tạo: " + ((DateTime)lst.Rows[0]["CreatedDate"]).ToString("dd/MM/yyyy") : "";
        }
        private void kryptonButton3_Click(object sender, EventArgs e)
        {
            frmServiceDetail frm = new frmServiceDetail();
            ShowChildForm(frm);
        }

        private void kryptonButton2_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Bạn có chắc là muốn xóa không?", "Thông Báo", MessageBoxButtons.YesNo);
            if (dlg == DialogResult.Yes)
            {
                string hangmuc = "";
                for (int i = 0; i < gridHangMuc.RowCount; i++)
                {
                    DataGridViewCheckBoxCell checkSelect = gridHangMuc.Rows[i].Cells[0] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value != null && (bool)checkSelect.Value == true)
                    {
                        int ID = !string.IsNullOrEmpty((string)gridHangMuc["Id", i].Value) ? int.Parse((string)gridHangMuc["Id", i].Value) : -1;
                        if (ID != -1)
                        {
                            PT_ServiceListEntity obj = PT_ServiceListManager.CreateInstant().GetByID(ID);
                            if (obj != null)
                            {
                                obj.IsDeleted = true;
                                obj.UpdatedBy = SessionLogin.UserCode;
                                obj.UpdatedDate = DateTime.Now;
                                PT_ServiceListManager.CreateInstant().Update(obj);
                                if (!string.IsNullOrEmpty(hangmuc))
                                    hangmuc += ", ";
                                hangmuc += obj.ServiceName;
                            }
                        }
                    }
                }
                LoadHangMuc();
                //history
                if (!string.IsNullOrEmpty(hangmuc))
                {
                    PT_ActionHistoryManager.CreateInstant().SaveHistory(SessionLogin.UserId, "Xóa hạng mục sửa chữa", "Xóa các hạng mục sau: " + hangmuc);
                }
            }
        }
        private void gridHangMuc_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1 && gridHangMuc.Columns[e.ColumnIndex].Name == "checkSelectHM")
            {
                for (int i = 0; i < gridHangMuc.RowCount; i++)
                {
                    DataGridViewCheckBoxCell checkSelect = gridHangMuc.Rows[i].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value == null || (checkSelect.Value != null && (bool)checkSelect.Value == false))
                        checkSelect.Value = true;
                    else
                        checkSelect.Value = false;
                }
            }
        }

        private void gridHangMuc_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex > 0 && e.RowIndex > -1)
            {
                int ID = !string.IsNullOrEmpty((string)gridHangMuc["Id", e.RowIndex].Value) ? int.Parse((string)gridHangMuc["Id", e.RowIndex].Value) : -1;
                string ServiceCode = !string.IsNullOrEmpty((string)gridHangMuc["ServiceCode", e.RowIndex].Value) ? gridHangMuc["ServiceCode", e.RowIndex].Value.ToString() : "";
                string Model = !string.IsNullOrEmpty((string)gridHangMuc["MotorType", e.RowIndex].Value) ? gridHangMuc["MotorType", e.RowIndex].Value.ToString() : "";
                if (Model == "Tất cả")
                {
                    Model = "ALL";
                }
                frmServiceDetail frm = new frmServiceDetail(ID, ServiceCode, Model, true);
                ShowChildForm(frm);
            }
        }

        private void btSelectFile_Click(object sender, EventArgs e)
        {
            openFileImport.ShowDialog();
        }

        private void openFileImport_FileOk(object sender, CancelEventArgs e)
        {
            ExcelHelper excel = new ExcelHelper();
            excel.Filename = openFileImport.FileName;
            DataTable dt = excel.ReadExcelBySheet(excel.GetAllSheet().Rows[0]["TABLE_NAME"].ToString().Replace("$", ""));
            dtHangMuc = dt.Copy();
            DialogResult dlg = MessageBox.Show("Bạn có muốn kiểm tra tính đúng đắn của dữ liệu trước khi import không?", "Thông Báo", MessageBoxButtons.YesNo);
            if (dlg == DialogResult.Yes)
            {
                // check file before import
                ShowStatusBar("Đang kiểm tra dữ liệu đầu vào");
                Thread t = new Thread(new ParameterizedThreadStart(CheckData));
                t.Start(dt);
                //CheckData(dt);
            }
            else
            {
                // import file without check 
                ImportData(dt);
                // history
                PT_ActionHistoryManager.CreateInstant().SaveHistory(SessionLogin.UserId, "Cập nhật bảng giá tiền công sửa chữa", "Import from excel");
            }
            LoadHangMuc();
        }
        private bool checkLoaiXe(string loaixe)
        {
            if (string.IsNullOrEmpty(loaixe))
                return false;
            PT_HondaModelEntity option = new PT_HondaModelEntity();
            option.IsDeleted = false;
            option.ModelCode = loaixe;
            DataTable dt = PT_HondaModelManager.CreateInstant().SelectWithCondition(option);
            if (dt.Rows.Count == 0)
                return false;
            return true;
        }
        private bool checkDichVu(string madichvu)
        {
            if (madichvu.CompareTo("SC") == 0)
                return true;
            else if (madichvu.CompareTo("RB") == 0)
                return true;
            else if (madichvu.CompareTo("GCN") == 0)
                return true;
            else if (madichvu.CompareTo("KTDK") == 0)
                return true;
            return false;
        }
        private void CheckData(object param)
        {
            DataTable dt = (DataTable)param;
            dt.Columns.Add("Columnmark");
            string lstColumn = "";
            int errorNumber = 0;
            this.Invoke((MethodInvoker)delegate
            { 
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    int STT = !string.IsNullOrEmpty(dt.Rows[i][0].ToString()) ? AF.Library.FString.IsInteger(dt.Rows[i][0].ToString()) ? int.Parse(dt.Rows[i][0].ToString()) : 0 : 0;
                    if (STT != 0)
                    {
                        bool flag = true;
                        lstColumn = "";
                        string serviceCode = dt.Rows[i][1].ToString();
                        string MotorType = dt.Rows[i][2].ToString();
                        string serviceName = dt.Rows[i][3].ToString();
                        decimal GiaTri = AF.Library.FString.IsInteger(dt.Rows[i][4].ToString().Replace(".", "").Replace(",", "")) ? AF.Library.FNumber.ConvertDecimal(dt.Rows[i][4].ToString().Replace(".", "").Replace(",", "")) : -1;
                        decimal GiaBan = AF.Library.FString.IsInteger(dt.Rows[i][5].ToString().Replace(".", "").Replace(",", "")) ? AF.Library.FNumber.ConvertDecimal(dt.Rows[i][5].ToString().Replace(".", "").Replace(",", "")) : -1;
                        int IsEditNoiDung = AF.Library.FString.IsInteger(dt.Rows[i][6].ToString()) && (dt.Rows[i][6].ToString().Trim().CompareTo("0") == 0 || dt.Rows[i][6].ToString().Trim().CompareTo("1") == 0) ? AF.Library.FNumber.ConvertInt(dt.Rows[i][6].ToString()) : -1;
                        int IsEditGiaBan = AF.Library.FString.IsInteger(dt.Rows[i][7].ToString()) && (dt.Rows[i][7].ToString().Trim().CompareTo("0") == 0 || dt.Rows[i][7].ToString().Trim().CompareTo("1") == 0) ? AF.Library.FNumber.ConvertInt(dt.Rows[i][7].ToString()) : 0;
                        int IsEditGiamGia = AF.Library.FString.IsInteger(dt.Rows[i][8].ToString()) && (dt.Rows[i][8].ToString().Trim().CompareTo("0") == 0 || dt.Rows[i][8].ToString().Trim().CompareTo("1") == 0) ? AF.Library.FNumber.ConvertInt(dt.Rows[i][8].ToString()) : 0;
                        int IsEditGCN = AF.Library.FString.IsInteger(dt.Rows[i][9].ToString()) && (dt.Rows[i][9].ToString().Trim().CompareTo("0") == 0 || dt.Rows[i][9].ToString().Trim().CompareTo("1") == 0) ? AF.Library.FNumber.ConvertInt(dt.Rows[i][9].ToString()) : 0;
                        string ServiceType = dt.Rows[i][10].ToString();
                        if (string.IsNullOrEmpty(serviceCode))
                        {
                            flag = false;
                            if (lstColumn != "")
                                lstColumn += ",";
                            lstColumn += "2";
                        }
                        // check loai xe
                        if (string.IsNullOrEmpty(MotorType))
                        {
                            flag = false;
                            if (lstColumn != "")
                                lstColumn += ",";
                            lstColumn += "3";
                        }
                        else
                        {
                            if (MotorType.CompareTo("ALL") != 0 && !checkLoaiXe(MotorType))
                            {
                                flag = false;
                                if (lstColumn != "")
                                    lstColumn += ",";
                                lstColumn += "3";
                            }
                        }
                        // check ten dich vu
                        if (string.IsNullOrEmpty(serviceName))
                        {
                            flag = false;
                            if (lstColumn != "")
                                lstColumn += ",";
                            lstColumn += "4";
                        }
                        // check gia tri
                        if (GiaTri <= -1)
                        {
                            flag = false;
                            if (lstColumn != "")
                                lstColumn += ",";
                            lstColumn += "5";
                        }
                        // check gia ban
                        if (GiaBan == -1)
                        {
                            flag = false;
                            if (lstColumn != "")
                                lstColumn += ",";
                            lstColumn += "6";
                        }

                        if (IsEditNoiDung == -1)
                        {
                            flag = false;
                            if (lstColumn != "")
                                lstColumn += ",";
                            lstColumn += "7";
                        }
                        if (IsEditGiaBan == -1)
                        {
                            flag = false;
                            if (lstColumn != "")
                                lstColumn += ",";
                            lstColumn += "8";
                        }
                        if (IsEditGiamGia == -1)
                        {
                            flag = false;
                            if (lstColumn != "")
                                lstColumn += ",";
                            lstColumn += "9";
                        }
                        if (IsEditGCN == -1)
                        {
                            flag = false;
                            if (lstColumn != "")
                                lstColumn += ",";
                            lstColumn += "10";
                        }
                        if (string.IsNullOrEmpty(ServiceType))
                        {
                            flag = false;
                            if (lstColumn != "")
                                lstColumn += ",";
                            lstColumn += "11";
                        }
                        else if (!checkDichVu(ServiceType))
                        {
                            flag = false;
                            if (lstColumn != "")
                                lstColumn += ",";
                            lstColumn += "11";
                        }
                        if (flag == false)
                        {
                            dt.Rows[i]["Columnmark"] = lstColumn;
                            errorNumber++;
                        }
                    }
                }
                if (errorNumber != 0)
                {
                    MessageBox.Show("Dữ liệu import chưa chính xác. Bấm OK để lấy file excel về và kiểm tra những dòng màu vàng!");
                    // xuất excel
                    saveFileExcel.FileName = "BangGiaTienCong_" + DateTime.Now.ToString("dd_MM_yyyy_HH_mm") + ".xls";
                    saveFileExcel.DefaultExt = "xls";
                    saveFileExcel.Filter = "Excel 2003 Files(*.xls)|*.xls|Excel 2007(*.xlsx)|*.xlsx|All Files|*.*";
                    saveFileExcel.AddExtension = true;
                    saveFileExcel.RestoreDirectory = true;
                    saveFileExcel.Title = "Chọn đường dẫn lưu file";
                    saveFileExcel.InitialDirectory = @"C:/";
                    if (saveFileExcel.ShowDialog() == DialogResult.OK)
                    {
                        if (saveFileExcel.FileName.Split('\\')[saveFileExcel.FileName.Split('\\').Length - 1] == ".xls")
                        {
                            MessageBox.Show("Nhập tên file cần lưu");
                        }
                        else
                        {
                            // Khoi dong Excel
                            ComExcel.Application exApp = new ComExcel.Application();

                            //// them file temp xls moi
                            //ComExcel.Workbook exBook = exApp.Workbooks.Add(ComExcel.XlWBATemplate.xlWBATWorksheet);

                            // Mo mot file Excel co san
                            //ComExcel.Workbook exBook = exApp.Workbooks.Add(ComExcel.XlWBATemplate.xlWBATWorksheet);
                            ComExcel.Workbook exBook = exApp.Workbooks.Add(Application.StartupPath + "/ExcelTemplate/BangGiaTienCongExport.xls");

                            // Lay sheet 1
                            ComExcel.Worksheet exSheet = (ComExcel.Worksheet)exBook.Worksheets[1];
                            //exSheet.Activate();

                            ////cau hình chung
                            //ComExcel.Range rng = (ComExcel.Range)exSheet.get_Range(exSheet.Cells[8, 1], exSheet.Cells[8 + dt.Rows.Count, HondaTypeList.Count]);
                            //rng.Interior.Pattern = ComExcel.Constants.xlSolid;
                            //rng.Borders.LineStyle = ComExcel.XlLineStyle.xlContinuous;
                            //rng.VerticalAlignment = ComExcel.XlVAlign.xlVAlignCenter;
                            //rng.HorizontalAlignment = ComExcel.XlHAlign.xlHAlignCenter;
                            ComExcel.Range rng = (ComExcel.Range)exSheet.get_Range(exSheet.Cells[6, 1], exSheet.Cells[dt.Rows.Count + 20, 11]);
                            rng.Font.Size = 9;
                            rng.WrapText = true;
                            // đổ dữ liệu
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                rng = (ComExcel.Range)exSheet.get_Range(exSheet.Cells[6 + i, 1], exSheet.Cells[6 + i, 11]);
                                rng.Interior.Pattern = ComExcel.Constants.xlSolid;
                                rng.Borders.LineStyle = ComExcel.XlLineStyle.xlContinuous;
                                int STT = !string.IsNullOrEmpty(dt.Rows[i][0].ToString()) ? AF.Library.FString.IsInteger(dt.Rows[i][0].ToString()) ? int.Parse(dt.Rows[i][0].ToString()) : 0 : 0;
                                if (STT != 0)
                                {
                                    if (!string.IsNullOrEmpty(dt.Rows[i]["Columnmark"].ToString().Trim()))
                                    {
                                        string[] markColumns = dt.Rows[i]["Columnmark"].ToString().Split(',');
                                        foreach (string item in markColumns)
                                        {
                                            ComExcel.Range rngItem = (ComExcel.Range)exSheet.Cells[6 + i, int.Parse(item)];
                                            rngItem.Cells.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
                                        }
                                    }
                                    exSheet.Cells[6 + i, 1] = dt.Rows[i][0].ToString();
                                    exSheet.Cells[6 + i, 2] = dt.Rows[i][1].ToString();
                                    exSheet.Cells[6 + i, 3] = dt.Rows[i][2].ToString();
                                    exSheet.Cells[6 + i, 4] = dt.Rows[i][3].ToString();
                                    exSheet.Cells[6 + i, 5] = dt.Rows[i][4].ToString();
                                    exSheet.Cells[6 + i, 6] = dt.Rows[i][5].ToString();
                                    exSheet.Cells[6 + i, 7] = dt.Rows[i][6].ToString();
                                    exSheet.Cells[6 + i, 8] = dt.Rows[i][7].ToString();
                                    exSheet.Cells[6 + i, 9] = dt.Rows[i][8].ToString();
                                    exSheet.Cells[6 + i, 10] = dt.Rows[i][9].ToString();
                                    exSheet.Cells[6 + i, 11] = dt.Rows[i][10].ToString();
                                }
                            }

                            exBook.SaveAs(saveFileExcel.FileName, ComExcel.XlFileFormat.xlWorkbookNormal, null, null, false, false, ComExcel.XlSaveAsAccessMode.xlExclusive, false, false, false, false, false);
                            // hien thi chuong trinh excel
                            exApp.Visible = true;
                            exBook.ReadOnlyRecommended = false;
                            //exBook.Close(false, false, false);
                            //exApp.Quit();
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(exBook);
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(exApp);
                        }
                    }
                }
                else
                {
                    DialogResult dlg = MessageBox.Show("Dữ liệu import đúng. Bạn có muốn import dữ liệu không?", "Thông Báo", MessageBoxButtons.YesNo);
                    if (dlg == DialogResult.Yes)
                    {
                        ContinuesImport();
                    }
                }
                EndShowStatusBar();
            });
            return;
        }
        public void ContinuesImport()
        {
            ImportData(dtHangMuc);
            // history
            PT_ActionHistoryManager.CreateInstant().SaveHistory(SessionLogin.UserId, "Cập nhật bảng giá tiền công sửa chữa", "Import from excel");
        }
        private void ImportData(DataTable dt)
        {
            try
            {
                PT_ServiceListManager.CreateInstant().DeleteAll();
                PT_ServiceListEntity obj = null;
                string CurrentServiceCode = "";
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    int STT = !string.IsNullOrEmpty(dt.Rows[i][0].ToString()) ? AF.Library.FString.IsInteger(dt.Rows[i][0].ToString()) ? int.Parse(dt.Rows[i][0].ToString()) : 0 : 0;
                    if (STT != 0)
                    {
                        string serviceCode = dt.Rows[i][1].ToString();
                        string MotorType = dt.Rows[i][2].ToString();
                        string serviceName = dt.Rows[i][3].ToString();
                        decimal GiaTri = AF.Library.FString.IsInteger(dt.Rows[i][4].ToString().Replace(".", "").Replace(",", "")) ? AF.Library.FNumber.ConvertDecimal(dt.Rows[i][4].ToString().Replace(".", "").Replace(",", "")) : -1;
                        decimal GiaBan = AF.Library.FString.IsInteger(dt.Rows[i][5].ToString().Replace(".", "").Replace(",", "")) ? AF.Library.FNumber.ConvertDecimal(dt.Rows[i][5].ToString().Replace(".", "").Replace(",", "")) : -1;
                        int IsEditNoiDung = AF.Library.FString.IsInteger(dt.Rows[i][6].ToString()) ? AF.Library.FNumber.ConvertInt(dt.Rows[i][6].ToString()) : 0;
                        int IsEditGiaBan = AF.Library.FString.IsInteger(dt.Rows[i][7].ToString()) ? AF.Library.FNumber.ConvertInt(dt.Rows[i][7].ToString()) : 0;
                        int IsEditGiamGia = AF.Library.FString.IsInteger(dt.Rows[i][8].ToString()) ? AF.Library.FNumber.ConvertInt(dt.Rows[i][8].ToString()) : 0;
                        int IsEditGCN = AF.Library.FString.IsInteger(dt.Rows[i][9].ToString()) ? AF.Library.FNumber.ConvertInt(dt.Rows[i][9].ToString()) : 0;
                        string ServiceType = dt.Rows[i][10].ToString();
                        if (!string.IsNullOrEmpty(serviceCode) && !string.IsNullOrEmpty(MotorType) && !string.IsNullOrEmpty(serviceName)
                           && GiaTri != -1 && GiaBan != -1)
                        {
                            // add serviceList
                            if (serviceCode != CurrentServiceCode)
                            {
                                CurrentServiceCode = serviceCode;
                                obj = new PT_ServiceListEntity();
                                obj.ServiceCode = serviceCode;
                                obj.ServiceName = serviceName;
                                obj.CanEditNoiDung = IsEditNoiDung == 0 ? false : true;
                                obj.CanEditGiaBan = IsEditGiaBan == 0 ? false : true;
                                obj.CanEditGiamGia = IsEditGiamGia == 0 ? false : true;
                                obj.CanEditGCN = IsEditGCN == 0 ? false : true;
                                obj.ServiceType = ServiceType;
                                obj.CreatedBy = SessionLogin.UserCode;
                                obj.CreatedDate = DateTime.Now;
                                PT_ServiceListManager.CreateInstant().Insert(obj);
                            }

                            PT_Service_ModelEntity smObj = new PT_Service_ModelEntity();
                            smObj.ServiceCode = serviceCode;
                            smObj.ModelCode = MotorType;
                            smObj.AgentPrice = (double)GiaTri;
                            smObj.Price = (double)GiaBan;
                            PT_Service_ModelManager.CreateInstant().Insert(smObj);
                        }

                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra trong lúc import dữ liệu. Vui lòng thử lại");
            }
        }
        private void btSearchHM_Click(object sender, EventArgs e)
        {
            string ServiceCode = cmbMaHangMuc.Text;
            if (ServiceCode.CompareTo("Tất cả") == 0)
                ServiceCode = "";
            string modelCode = cmbModel.Text;
            if (modelCode.CompareTo("Tất cả") == 0)
                modelCode = "";
            DataTable lst = PT_ServiceListManager.CreateInstant().SearchByServiceAndModel(ServiceCode, modelCode);
            DataTable dt = new DataTable();
            dt.Columns.Add("Id");
            dt.Columns.Add("STT");
            dt.Columns.Add("ServiceCode");
            dt.Columns.Add("MotorType");
            dt.Columns.Add("ServiceName");
            dt.Columns.Add("AgentPrice");
            dt.Columns.Add("Price");
            dt.Columns.Add("ServiceType");
            dt.Columns.Add("CanEditNoiDung");
            dt.Columns.Add("CanEditGiaBan");
            dt.Columns.Add("CanEditGiamGia");
            dt.Columns.Add("CanEditGCN");
            for (int i = 0; i < lst.Rows.Count; i++)
            {
                DataRow dr = dt.NewRow();
                dr["Id"] = lst.Rows[i]["Id"].ToString();
                dr["STT"] = (i + 1).ToString();
                dr["ServiceCode"] = lst.Rows[i]["ServiceCode"].ToString();
                if (lst.Rows[i]["ModelCode"].ToString().CompareTo("ALL") == 0)
                    dr["MotorType"] = "Tất cả";
                else
                    dr["MotorType"] = lst.Rows[i]["ModelCode"].ToString();
                dr["ServiceName"] = lst.Rows[i]["ServiceName"];
                dr["AgentPrice"] = String.Format("{0:0,0.###}", double.Parse(lst.Rows[i]["AgentPrice"].ToString()));
                dr["Price"] = String.Format("{0:0,0.###}", double.Parse(lst.Rows[i]["Price"].ToString()));
                string type = "";
                switch (lst.Rows[i]["ServiceType"].ToString())
                {
                    case "SC":
                        type = "Sửa chữa";
                        break;
                    case "RB":
                        type = "Ráp bán";
                        break;
                    case "KTDK":
                        type = "Kiểm tra định kỳ";
                        break;
                    case "GCN":
                        type = "Gia công ngoài";
                        break;
                }
                dr["ServiceType"] = type;

                string CanEditNoiDung = "";
                switch (bool.Parse(lst.Rows[i]["CanEditNoiDung"].ToString()))
                {
                    case true:
                        CanEditNoiDung = "Có";
                        break;
                    case false:
                        CanEditNoiDung = "Không";
                        break;
                }
                dr["CanEditNoiDung"] = CanEditNoiDung;

                string CanEditGiaBan = "";
                switch (bool.Parse(lst.Rows[i]["CanEditGiaBan"].ToString()))
                {
                    case true:
                        CanEditGiaBan = "Có";
                        break;
                    case false:
                        CanEditGiaBan = "Không";
                        break;
                }
                dr["CanEditGiaBan"] = CanEditGiaBan;

                string CanEditGiamGia = "";
                switch (bool.Parse(lst.Rows[i]["CanEditGiamGia"].ToString()))
                {
                    case true:
                        CanEditGiamGia = "Có";
                        break;
                    case false:
                        CanEditGiamGia = "Không";
                        break;
                }
                dr["CanEditGiamGia"] = CanEditGiamGia;

                string CanEditGCN = "";
                switch (bool.Parse(lst.Rows[i]["CanEditGCN"].ToString()))
                {
                    case true:
                        CanEditGCN = "Có";
                        break;
                    case false:
                        CanEditGCN = "Không";
                        break;
                }
                dr["CanEditGCN"] = CanEditGCN;
                dt.Rows.Add(dr);
            }
            gridHangMuc.DataSource = dt;
        }
        public void LoadDefault()
        {
            DataTable dt = PT_ServiceListManager.CreateInstant().GetAll2();
            cmbMaHangMuc.DataSource = dt;
            DataRow dr = dt.NewRow();
            dr["ServiceCode"] = "Tất cả";
            dt.Rows.InsertAt(dr, 0);
            cmbMaHangMuc.ValueMember = "ServiceCode";
            cmbMaHangMuc.DisplayMember = "ServiceCode";
            cmbMaHangMuc.SelectedIndex = 0;

            dt = PT_HondaModelManager.CreateInstant().GetAll();
            cmbModel.DataSource = dt;
            dr = dt.NewRow();
            dr["ModelCode"] = "Tất cả";
            dt.Rows.InsertAt(dr, 0);
            cmbModel.ValueMember = "ModelCode";
            cmbModel.DisplayMember = "ModelCode";
            cmbModel.SelectedIndex = 0;
        }
        private void btDownLoadFileMau_Click(object sender, EventArgs e)
        {
            // Khoi dong Excel
            ComExcel.Application exApp = new ComExcel.Application();

            //// them file temp xls moi
            //ComExcel.Workbook exBook = exApp.Workbooks.Add(ComExcel.XlWBATemplate.xlWBATWorksheet);

            // Mo mot file Excel co san
            //ComExcel.Workbook exBook = exApp.Workbooks.Add(ComExcel.XlWBATemplate.xlWBATWorksheet);
            ComExcel.Workbook exBook = exApp.Workbooks.Add(Application.StartupPath + "/ExcelTemplate/BangGiaTienCong.xls");
            // hien thi chuong trinh excel
            exApp.Visible = true;
            exBook.ReadOnlyRecommended = false;
            //exBook.SaveAs(saveFileExcel.FileName, ComExcel.XlFileFormat.xlWorkbookNormal, null, null, false, false, ComExcel.XlSaveAsAccessMode.xlExclusive, false, false, false, false, false);
            //exBook.Close(false, false, false);
            //exApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(exBook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(exApp);
        } 
        #endregion

        private void btThemPTKMGT_Click(object sender, EventArgs e)
        {
            frmToolGTKM frm = new frmToolGTKM();
            this.ShowChildForm(frm);
        }

        private void btDelPTKMGT_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Bạn có chắc là muốn xóa không?", "Thông Báo", MessageBoxButtons.YesNo);
            if (dlg == DialogResult.Yes)
            {
                string PT = "";
                for (int i = 0; i < dtPTKMGT.RowCount; i++)
                {
                    DataGridViewCheckBoxCell checkSelect = dtPTKMGT.Rows[i].Cells["CheckSelectPTGTKM"] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value != null && (bool)checkSelect.Value == true)
                    {
                        int ID = !string.IsNullOrEmpty(dtPTKMGT["IdPTKMGT", i].Value.ToString()) ? (int)dtPTKMGT["IdPTKMGT", i].Value : -1;
                        if (ID != -1)
                        {
                            PT_ToolKMGTEntity obj = PT_ToolKMGTManager.CreateInstant().GetByID(ID);
                            if (obj != null)
                            {
                                obj.IsDeleted = true;
                                obj.UpdatedBy = SessionLogin.UserCode;
                                obj.UpdatedDate = DateTime.Now;
                                PT_ToolKMGTManager.CreateInstant().Update(obj);
                                if (!string.IsNullOrEmpty(PT))
                                    PT += ", ";
                                PT += obj.Name;
                            }
                        }
                    }
                }
                if (!string.IsNullOrEmpty(PT))
                    PT_ActionHistoryManager.CreateInstant().SaveHistory(SessionLogin.UserId, "Xóa phụ tùng giảm trừ khuyến mãi", "Xóa các phụ tùng sau:" + PT);
                LoadPTGTKM();
            }
        }
        private void LoadPTGTKM()
        {
            DataTable dt = PT_ToolKMGTManager.CreateInstant().GetAll();
            dtPTKMGT.DataSource = dt;
        }

        private void dtPTKMGT_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1 && dtPTKMGT.Columns[e.ColumnIndex].Name == "CheckSelectPTGTKM")
            {
                for (int i = 0; i < dtPTKMGT.RowCount; i++)
                {
                    DataGridViewCheckBoxCell checkSelect = dtPTKMGT.Rows[i].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value == null || (checkSelect.Value != null && (bool)checkSelect.Value == false))
                        checkSelect.Value = true;
                    else
                        checkSelect.Value = false;
                }
            }
        }

        private void dtPTKMGT_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex > 0 && e.RowIndex > -1)
            {
                string Code = !string.IsNullOrEmpty(dtPTKMGT["CodePTKMGT", e.RowIndex].Value.ToString()) ? (string)dtPTKMGT["CodePTKMGT", e.RowIndex].Value : "";
                frmToolGTKM frm = new frmToolGTKM(Code, true);
                this.ShowChildForm(frm);
            }
        }

        private void btThemPKTT_Click(object sender, EventArgs e)
        {
            frmToolPKTT frm = new frmToolPKTT();
            this.ShowChildForm(frm);
        }

        private void btXoaPKTT_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Bạn có chắc là muốn xóa không?", "Thông Báo", MessageBoxButtons.YesNo);
            if (dlg == DialogResult.Yes)
            {
                string PT = "";
                for (int i = 0; i < gridPKTT.RowCount; i++)
                {
                    DataGridViewCheckBoxCell checkSelect = gridPKTT.Rows[i].Cells["CheckSelectPKTT"] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value != null && (bool)checkSelect.Value == true)
                    {
                        int ID = !string.IsNullOrEmpty(gridPKTT["IdPKTT", i].Value.ToString()) ? (int)gridPKTT["IdPKTT", i].Value : -1;
                        if (ID != -1)
                        {
                            PT_ToolPKTTEntity obj = PT_ToolPKTTManager.CreateInstant().GetByID(ID);
                            if (obj != null)
                            {
                                obj.IsDeleted = true;
                                obj.UpdatedBy = SessionLogin.UserCode;
                                obj.UpdatedDate = DateTime.Now;
                                PT_ToolPKTTManager.CreateInstant().Update(obj);
                                if (!string.IsNullOrEmpty(PT))
                                    PT += ", ";
                                PT += obj.Name;
                            }
                        }
                    }
                }
                if (!string.IsNullOrEmpty(PT))
                    PT_ActionHistoryManager.CreateInstant().SaveHistory(SessionLogin.UserId, "Xóa phụ kiện trang trí", "Xóa các phụ tùng sau:" + PT);
                LoadPTPKTT();
            }
        }

        private void LoadPTPKTT()
        {
            DataTable dt = PT_ToolPKTTManager.CreateInstant().GetAll();
            gridPKTT.DataSource = dt;
        }

        private void gridPKTT_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1 && gridPKTT.Columns[e.ColumnIndex].Name == "CheckSelectPKTT")
            {
                for (int i = 0; i < gridPKTT.RowCount; i++)
                {
                    DataGridViewCheckBoxCell checkSelect = gridPKTT.Rows[i].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
                    if (checkSelect.Value == null || (checkSelect.Value != null && (bool)checkSelect.Value == false))
                        checkSelect.Value = true;
                    else
                        checkSelect.Value = false;
                }
            }
        }

        private void gridPKTT_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex > 0 && e.RowIndex > -1)
            {
                string Code = !string.IsNullOrEmpty(gridPKTT["CodePKTT", e.RowIndex].Value.ToString()) ? (string)gridPKTT["CodePKTT", e.RowIndex].Value : "";
                frmToolPKTT frm = new frmToolPKTT(Code, true);
                this.ShowChildForm(frm);
            }
        }

    }
}
